<?php
/*
#生成EXCEL2003版格式数据
#所有内容都要转换成GBK或GB2312的，再写入
*/
if(!defined('APP_HOME')) exit('Access Denied');
class lib_class_excel
{
    protected $xls = '';
    protected $xlsFile = NULL;

    /*
    #构造
    */
    public function __construct()
    {
        $this->xls .= $this->xlsBegain();
    }

    /*
    #向单元格中写内容
    #$Row:行数  $Col:列数  $Value:内容
    */
    public function writeContent($Row, $Col, $Value)
    {
       if(is_numeric($Value)){
            $this->xls .= $this->xlsWriteNumber($Row, $Col, $Value);
       }elseif(is_string($Value)){
            $this->xls .= $this->xlsWriteLabel($Row, $Col, $Value);
       }else{
            $Value = (string) $Value;
            $this->xls .= $this->xlsWriteLabel($Row, $Col, $Value);
       }
       return $this->xls;
    }

    /*
    #将EXCEL存成文件
    */
    public function saveFile($fileName)
    {
        $this->xls .= $this->xlsEnd();

        if(file_exists($fileName)){
            $len = file_put_contents($this->xls);
            $this->xlsFile = $fileName;
            return $len;
        }
        return false;
    }

    /*
    #将EXCEL下载成文件
    */
    public function downFile($fileName)
    {
        $this->xls .= $this->xlsEnd();

        $fileName = basename($fileName);
        if('.xls' != substr($fileName, -4)) $fileName .= '.xls';
        header ('Content-type: application/x-msexcel');
        header ("Content-Disposition: attachment; filename={$fileName}" );
        header ("Content-Description: PHP/INTERBASE Generated Data" );
        if(NULL === $this->xlsFile) echo $this->xls;
        else readfile($this->xlsFile);
    }

    /*
    #开始EXCEL文件
    */
    public function xlsBegain()
    {
        return pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    }

    /*
    #结束EXCEL文件
    */
    public function xlsEnd() {
        return pack("ss", 0x0A, 0x00);
    }

    /*
    #向单元格中写入数字内容
    */
    public function xlsWriteNumber($Row, $Col, $Value)
    {
        $text = '';
        $text .= pack("sssss", 0x203, 14, $Row, $Col, 0x0);
        $text .= pack("d", $Value);
        return $text;
    }

    /*
    #向单元格中写入字符内容
    */
    public function xlsWriteLabel($Row, $Col, $Value)
    {
        $text = '';
        $L = strlen($Value);
        $text .= pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
        $text .= $Value;
        return $text;
    }

    /*
    #析构
    */
    public function __destruct()
    {
       $this->xls = '';
       return true;
    }

}

?>
